import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME
} from '@/config/app';
import {
	toLogin,
	checkLogin
} from '../libs/login';
import store from '../store';


/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false,
	loading = false
}) {
	let Url = HTTP_REQUEST_URL,
		header = HEADER;
	// if (!noAuth) {
	// 	//登录过期自动登录
	// 	if (!store.state.app.token && !checkLogin()) {
	// 		toLogin();
	// 		return Promise.reject({
	// 			msg: '未登录'
	// 		});
	// 	}
	// }
	// 加载效果
	if (loading) {
		uni.showLoading({
			title: loadText || '加载中'
		});
	}
	if (store.state.app.token) header[TOKENNAME] ='Bearer '+store.state.app.token;
	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				const status = res.data.code
				if (noVerify) {
					reslove(res.data, res);
				} else if (status == 1) { //成功标识，一般为200，根据实际项目而定
					reslove(res.data, res);
				} else if (status == 405) {
					// 登录过期处理
					store.commit('LOGOUT')
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/auth/mplogin'
						})
					}, 500)

				} else if ([410000, 410001, 410002].indexOf(status) !== -1) {
					toLogin();
					reject(res.data);
				} else if (status == 410010) {
					console.log(3)
					uni.showModal({
						title: '提示',
						content: res.data.msg,
						showCancel: false,
						confirmText: '我知道了'
					});
				} else {
					const filterUrl=['/api/lottery/add_user_lottery','/api/login','/api/lottery/info/1']
					if(!filterUrl.includes(url)){
						// console.log(url,"jskdjfksdj");
						// 展示错误信息
						uni.showToast({
							title: res.data.info,
							icon: "none"
						})
					}
					

					reject(res.data.info || '系统错误');
				}

			},
			fail: (msg) => {
				let data = {
					mag: '请求失败',
					status: 1 //1没网
				}
				// #ifdef APP-PLUS
				reject(data);
				// #endif
				// #ifndef APP-PLUS
				reject(msg);
				// #endif
			},
			complete() {
				// uni.hideLoading()
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;